import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '../views/Login.vue'
import { checktoken } from '../apis/users'

Vue.use(VueRouter)
//获取原型对象上的push函数
const originalPush = VueRouter.prototype.push
//修改原型对象中的push方法
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}


const routes = [
  {
    path: '/',
    name: 'Login',
    component: Login
  },
  {
    path: '/home',
    name: 'Home',
    //懒加载
    component: () => import('../views/Home.vue'),
    children: [
      //首页
      { path: 'main', name: 'main', component: () => import('../views/modules/main/Main.vue') },
      //账号列表
      { path: 'accountlist', name: 'accountlist', component: () => import('../views/modules/account/AccountList.vue') },
      //修改账号
      { path: 'accountpwd', name: 'accountpwd', component: () => import('../views/modules/account/AccountPwd.vue') },
      //添加账号
      { path: 'Addaccount', name: 'Addaccount', component: () => import('../views/modules/account/AddAccount.vue') },

      //店铺管理
      { path: 'StoreManagement', name: 'StoreManagement', component: () => import('../views/modules/store/StoreManagement.vue') },

      //商品列表
      { path: 'goodslist', name: 'goodslist', component: () => import('../views/modules/goods/GoodsList.vue') },
      //商品分类
      { path: 'goodscategory', name: 'goodscategory', component: () => import('../views/modules/goods/GoodsCategory.vue') },
      //添加商品
      { path: 'AddGoods', name: 'AddGoods', component: () => import('../views/modules/goods/AddGoods.vue') },

      //订单管理
      { path: 'order', name: 'order', component: () => import('../views/modules/order/Order.vue') },

      //商品统计
      { path: 'CommodityStats', name: 'CommodityStats', component: () => import('../views/modules/sales/CommodityStats.vue') },
      { path: 'orderStats', name: 'orderStats', component: () => import('../views/modules/sales/orderStats.vue') },

      //用户信息
      { path: 'userinfo', name: 'userinfo', component: () => import('../views/modules/account/UserInfo.vue') },

    ]

  },
  {
    path: '*',
    name: '404',
    component: () => import('../views/Error404.vue')
  }
]

const router = new VueRouter({
  routes
})

//路由拦截
router.beforeEach((to, from, next) => {
  //to: 即将前往的路由地址
  //from: 你之前的路由地址
  //next: 函数，是否允许跳转
  // console.log(to, from, next)

  //除开登录，其他全部进行登录验证
  if (to.path == '/') {
    next()  //直接放行
  } else {
    //其他所有hash都要验证是否登录，在登录状态，才允许访问，否则拦截


    checktoken({ token: localStorage.token }).then(res => {
      if (res.data.code == 0) {
        //还在登录状态
        next()
      } else {
        //跳转到登录页面
        next('/')
      }
    })

  }


})

export default router
